import FormItem from 'antd/es/form/FormItem'
import useUserStore from '@/store/useUserStore'
import { Button, Form, Input } from 'antd'
import { FC } from 'react'
import type { RequestLoginForm } from '@/apis/login/types'
import { login } from '@/apis/login'

import './index.scss'

const Login: FC = () => {
  const navigate = useNavigate()

  const { setToken, setUserInfo } = useUserStore(state => ({
    setToken: state.setToken,
    setUserInfo: state.setUserInfo
  }))

  const [visibility, setVisibility] = useState(false)

  const [isLoginSuccess, setLoginState] = useState(false)
  const saveUserInfo = async (values: RequestLoginForm) => {
    const result = (await login(values)) as string
    setToken(result)
    await setUserInfo()
    setLoginState(true)
  }
  const { loading, run: fetchUserInfo } = useRequest(saveUserInfo, {
    manual: true
  })
  const handleFormValidSuccess = (values: RequestLoginForm) => {
    if (isLoginSuccess) return
    fetchUserInfo(values)
    useMessage({
      content: '登录成功',
      onClose: () => navigate('/home')
    })
  }

  return (
    <main className="login-main">
      <div className="login-header">祥和环保APP</div>
      <div className="login-container">
        <Form
          name="login"
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 20 }}
          onFinish={handleFormValidSuccess}
          autoComplete="off"
        >
          <FormItem
            label="账号"
            name="account"
            colon={false}
            rules={[{ required: true, message: '请输入账号' }]}
            hasFeedback
          >
            <Input placeholder="请输入账号" />
          </FormItem>
          <FormItem
            label="密码"
            name="password"
            colon={false}
            rules={[{ required: true, message: '请输入密码' }]}
            hasFeedback
          >
            <Input.Password
              placeholder="请输入密码"
              visibilityToggle={{
                visible: visibility,
                onVisibleChange: setVisibility
              }}
            />
          </FormItem>
          <FormItem wrapperCol={{ span: 24 }}>
            <Button
              className="flex justify-center"
              type="primary"
              htmlType="submit"
              loading={loading}
              block
            >
              登录
            </Button>
          </FormItem>
        </Form>
      </div>
    </main>
  )
}

export default Login
